package com.atguigu.tingshu.album.service.impl;

import cn.hutool.core.util.IdUtil;
import com.atguigu.tingshu.album.config.MinioConstantProperties;
import com.atguigu.tingshu.album.service.FileUploadService;
import com.atguigu.tingshu.common.execption.GuiguException;
import io.minio.BucketExistsArgs;
import io.minio.MakeBucketArgs;
import io.minio.MinioClient;
import io.minio.PutObjectArgs;
import io.minio.SetBucketPolicyArgs;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.Objects;

/**
 * @author 路飞
 * @date 2024/7/24 16:42
 * @description
 */
@Service
@Slf4j
public class FileUploadServiceImpl implements FileUploadService {

    @Autowired
    private MinioConstantProperties minioConstantProperties;

    @Autowired
    private MinioClient minioClient;

    @Override
    public String fileUpload(MultipartFile file) {
        try {
            BufferedImage read = ImageIO.read(file.getInputStream());
            if (Objects.isNull(read)) {
                throw new GuiguException(422, "上传文件不正确");
            }

            // 判断minio中桶是否存在
            boolean found =
                    minioClient.bucketExists(BucketExistsArgs.builder().bucket(minioConstantProperties.getBucketName()).build());
            if (!found) {
                String policy = "{\"Version\":\"2012-10-17\",\"Statement\":[{\"Effect\":\"Allow\",\"Principal\":{\"AWS\":[\"*\"]},\"Action\":[\"s3:GetObject\"],\"Resource\":[\"arn:aws:s3:::" + minioConstantProperties.getBucketName() + "/*\"]}]}";
                // 如果桶不存在，则创建这个桶，并且设置桶的访问策略
                minioClient.makeBucket(MakeBucketArgs.builder().bucket(minioConstantProperties.getBucketName()).build());
                minioClient.setBucketPolicy(SetBucketPolicyArgs.builder()
                        .bucket(minioConstantProperties.getBucketName())
                        .config(policy)
                        .build());
            } else {
                log.info("Bucket {} already exists.", minioConstantProperties.getBucketName());
            }

            String date = DateTimeFormatter.ofPattern("/yyyy/MM/dd/").format(LocalDate.now());
            String fileNamePrefix = IdUtil.getSnowflakeNextIdStr();
            String objectName = date + fileNamePrefix + file.getOriginalFilename();

            minioClient.putObject(PutObjectArgs.builder()
                    .bucket(minioConstantProperties.getBucketName())
                    .stream(file.getInputStream(), file.getSize(), -1)
                    .object(objectName)
                    .build());

            String filePath = minioConstantProperties.getEndpointUrl() + "/" + minioConstantProperties.getBucketName() + objectName;
            log.info("fileUpload filePath {}", filePath);
            return filePath;
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }
}
